<template>
    <div class="affix-container">
        <zh-header-toolbar>
            <zh-button style="margin-left: 8px" button-type="add" @click="functionAdd">新增
            </zh-button>
            <zh-button style="margin-left: 8px" button-type="del" @click="deleteFunction">删除
            </zh-button>
            <zh-button style="margin-left: 8px" button-type="save" @click="editFunction">编辑</zh-button>
            <zh-button style="margin-left: 8px" v-if="state.infoFlag" icon="ele-Refresh" type="warning"
                       @click="clearFunctionCache">清除缓存
            </zh-button>
            <zh-button style="margin-left: 8px" v-if="state.routerFlag" button-type="add" @click="openRouterModel">
                关联路由
            </zh-button>
        </zh-header-toolbar>
        <zh-space style="padding-top: 10px">
            <zh-card title="">
                <zh-form ref="functionForm" :model="state.queryParam">
                    <zh-form-input prop="funcTitle" label="功能名称" placeholder="支持模糊查询"
                                   v-model="state.queryParam.funcTitle"></zh-form-input>
                    <zh-form-input prop="funcCode" label="功能编号" v-model="state.queryParam.funcCode"></zh-form-input>
                    <template v-if="state.advanced">
                      <zh-form-select prop="funcCode" label="功能来源类型" :options="state.funcSourceTypeOpt"
                                    v-model="state.queryParam.funcSourceType" placeholder="请选择功能来源类型"></zh-form-select>
                      <zh-form-select prop="funcStatus" label="有效状态" :options="state.funcStatusDict"
                                    v-model="state.queryParam.funcStatus" placeholder="请选择有效状态"></zh-form-select>
                      <zh-form-input prop="serviceName" label="服务名" placeholder="支持模糊查询"
                                   v-model="state.queryParam.serviceName"></zh-form-input>
                      <zh-form-select
                        prop="appId"
                        :remote="true"
                        label="所属应用"
                        :timeout="20000"
                        v-model="state.queryParam.appId"
                        :defaultFields="{ label: 'appName', value: 'appId' }"
                        funcCode="application0012"
                        searchField="appName"
                      ></zh-form-select>
                      <zh-form-select placeholder="请搜索，单选"
                        funcCode="org0001"
                        label="所在单位组织"
                        prop="orgId"
                        :timeout="20000"
                        searchField="orgName"
                        :fieldNames="{
                          label: 'orgName',
                          value: 'orgId',
                        }"
                        :lazy="true"
                        v-model="state.queryParam.orgId">
                      </zh-form-select>
                      <zh-form-select prop="publicFlag" label="是否公共" :options="state.flagDict"
                                    v-model="state.queryParam.publicFlag" placeholder="请选择"></zh-form-select>
                      <zh-form-select prop="checkPrivilegeFlag" label="是否权限控制" :options="state.flagDict"
                                    v-model="state.queryParam.checkPrivilegeFlag" placeholder="请选择"></zh-form-select>
                    </template>
                    <zh-form-query v-model="state.advanced"  :form-ref="functionForm" @queryClick="clearData"
                                   :table-ref="functionTable"></zh-form-query>
                </zh-form>
            </zh-card>
            <zh-table
                ref="functionTable"
                title="功能列表"
                :height="600"
                funcCode="function0001"
                :columns="state.tableColumn"
                @radio-change="radioChangeEvent"
                :radio-config="{ trigger: 'row' }"
                :disabled="false"
                highlight-current-row
                @current-change="handleCurrentChange"
            >
                <template #status_edit="{ row }">
                    <el-switch
                        v-model="row.funcStatus"
                        active-text="启用"
                        inactive-text="禁用"
                        active-value="1"
                        inactive-value="0"
                        inline-prompt
                        size="large"
                        @change="onStatusChange(row)"
                        :width="50"
                    ></el-switch>
                </template>
            </zh-table>
        </zh-space>
        <el-dialog
            ref="dialog"
            v-model="state.dialogVisible"
            title="功能信息"
            width="100%"
        >
            <zh-card shadow="hover" style="height: 100%">
                <zh-header-toolbar>
                    <zh-button style="margin-left: 8px" button-type="save" @click="saveFunction">保存</zh-button>
                </zh-header-toolbar>
                <el-tabs v-model="activeName" @tab-click="tabsChange" :stretch="true" style="height: 100%">
                    <el-tab-pane label="基础信息" name="baseInfo" style="height: 100%">
                        <function-form ref="functionPage" scroll-height="60vh"/>
                    </el-tab-pane>
                    <el-tab-pane label="路由列表" name="routerList">
                        <function-router-form ref="routerForm" :select-node="state.selectNode"
                                              :functionInfo="state.functionInfo"></function-router-form>
                    </el-tab-pane>
                </el-tabs>
            </zh-card>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="indexList">
import FunctionForm from '@/views/system/config/function/component/FunctionForm.vue';
import FunctionRouterForm from '@/views/system/config/function/component/FunctionRouterForm.vue';
import {ElMessageBox,ElMessage} from 'element-plus';
import {loop} from '@/utils/util';
import {getCurrentInstance} from "vue";

const state = reactive({
    //功能来源类型：1 内部服务 2 第三方应用接入
    funcSourceTypeOpt: [
        {dictKey: '1', dictValue: '内部服务'},
        {dictKey: '2', dictValue: '第三方应用接入'}
    ],
    funcStatusDict: [
        {dictKey: '0', dictValue: '无效'},
        {dictKey: '1', dictValue: '有效'}
    ],
    flagDict: [
        {dictKey: '0', dictValue: '否'},
        {dictKey: '1', dictValue: '是'}
    ],
    advanced:true,
    //弹窗
    dialogVisible: false,
    description: '功能管理',
    // 基础信息操作按钮是否显示
    infoFlag: true,
    functionInfo: null as any,
    // 路由列表操作按钮是否显示
    routerFlag: false,
    // 功能树
    expandedKeys: [] as any[],
    selectNode: {} as any,
    searchValue: '',
    autoExpandParent: true,
    // 关联路由弹出框
    errors: [] as any[],
    //查询条件
    queryParam: {} as any,
    dictData: [],
    funcId: '',
    selectRow: {} as any,
    tableColumn: [
        {
            type: 'radio',
            width: 40,
            fixed: 'left',
            align: 'center',
        },
        {type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号'},
        {field: 'funcId', title: '方法Id', fixed: 'left', visible: false, align: 'center', width: 150},
        {field: 'funcCode', title: '功能编号', align: 'center', fixed: 'left', width: 150},
        {field: 'funcTitle', title: '功能名称', align: 'center', fixed: 'left', width: 150},
        {field: 'funcTypeName', title: '功能类型', align: 'center',  width: 150},
        //服务名 SERVICE_NAME
        {field: 'serviceName', title: '服务名', align: 'center',  width: 200},
        {field: 'visits', title: '每日访问上限次数', align: 'center',  width: 150},
        {
            field: 'funcStatus',
            title: '状态',
            align: 'center',
            editRender: {},
            slots: {
                // 使用插槽模板渲染
                default: 'status_edit',
                edit: 'status_edit',
            },
            width: 120,
        },
        {field: 'funcDesc', title: '功能描述', align: 'center',  width: 300},
        {field: 'funcSourceTypeName', title: '功能来源', align: 'center',  width: 120},
        {field: 'httpMethod', title: '调用方式', align: 'center',  width: 120},
        {field: 'timeout', title: '服务超时时间', align: 'center',  width: 120},
    ],
});

//------------------定义子组件---------------------------
const functionForm = ref<any>({});
const functionTable = ref<any>({});
const {isTagsview} = storeToRefs($store.theme);
const routerForm = ref();
const functionPage = ref();
const activeName = ref('baseInfo');
const saveType = ref('edit');
const { proxy } = <any>getCurrentInstance();


//------------------定义调用方法-------------------------
function radioChangeEvent({row}) {
    state.funcId = row.funcId;
    state.selectRow = row;
}

function handleCurrentChange(row) {
    state.selectRow = row;
    state.funcId = row.funcId;
}

// 启用/禁用 功能/接口
function onStatusChange(row) {
    const params = {
        funcId: row.funcId,
        status: row.funcStatus,
    };
    let text = '禁用';
    if (params.status == '1') {
        text = '启用';
    }
    setTimeout(() => {
        $api.common.send
            .post('function0011', params)
            .then(() => {
                $messageBox.success(text + '成功', '提示');
            })
            .catch(() => {});
    }, 200);
}

function clearFunctionCache() {
    const params: any = {};
    if (state.functionInfo) {
        params.funcId = state.functionInfo.funcId;
    }
    setTimeout(() => {
        //function0009
        $api.common.send.post('function0009',params)
            .then(() => {
                $messageBox.success('清除缓存成功', '提示');
            })
            .catch(() => {
            });
    }, 100);
}

function tabsChange() {
    if (activeName.value === 'baseInfo') {
        findFuncInfo();
        state.infoFlag = true;
        state.routerFlag = false;
    } else if (activeName.value === 'routerList') {
        findFuncInfo();
        routerForm.value.findRouterList();
        state.infoFlag = false;
        state.routerFlag = true;
    }
}

function findFuncInfo() {
    if (state.selectNode && state.selectNode.key) {
        const params = {
            funcId: state.selectNode.key,
        };
        $api.common.send.post('function0002',params).then((res) => {
            state.functionInfo = res.result;
            // 赋值子组件信息
            functionPage.value.setInitDate(res.result);
        }).catch(() => {});
    }
}

function editFunction() {
    if (state.funcId) {
        nextTick(()=>{
            state.selectNode = {
                key:state.funcId
            }
            findFuncInfo();
            console.log('state.selectNode',state.selectNode)
        });
    } else {
        ElMessageBox.confirm(
            '请先选择需要操作的功能',
            '提示',
            {
                confirmButtonText: '确定',
                type: 'warning',
                showCancelButton: false
            }
        ).then(() => {

        }).catch(() => {

        })
        return;
    }
    state.dialogVisible = true;
}

function openRouterModel() {
    routerForm.value.openRouterModel();
}

function saveFunction() {
    //表单验证
    functionPage.value.form.validate((valid) => {
        if (valid) {
            const functionData: any = functionPage.value.functionInfo;
            if (functionData.logFlag) {
                functionData.logFlag = '1';
            } else {
                functionData.logFlag = '0';
            }
            if (functionData.rollbackFlag) {
                functionData.rollbackFlag = '1';
            } else {
                functionData.rollbackFlag = '0';
            }
            if (functionData.auditFlag) {
                functionData.auditFlag = '1';
            } else {
                functionData.auditFlag = '0';
            }
            if (functionData.spanRollbackFlag) {
                functionData.spanRollbackFlag = '1';
            } else {
                functionData.spanRollbackFlag = '0';
            }
            if (functionData.funcId) {
                setTimeout(() => {
                    $api.common.send.post('function0005',functionData)
                        .then((res) => {
                            $messageBox.success('修改成功', '提示');
                            functionPage.value.setInitDate(res.result);
                            state.functionInfo = functionPage.value.functionInfo;
                        })
                        .catch(() => {
                        });
                }, 10);
            } else {
                setTimeout(() => {
                    //function0004
                    $api.common.send.post('function0004',functionData)
                        .then((res) => {
                            $messageBox.success('新增成功', '提示');
                            functionPage.value.setInitDate(res.result);
                            state.functionInfo = functionPage.value.functionInfo;
                            state.selectNode = {
                                key:res.result.funcId
                            }
                        })
                        .catch(() => {
                        });
                }, 10);
            }
        }
    });
}

function functionAdd() {
    state.dialogVisible = true;
    saveType.value = 'add';
    console.log(functionPage)
    const params = {
        parentId: null as any,
        parentTitle: '',
        funcId: '',
        funcStatus: '1',
        publicFlag: '0',
        nodeType: '0',
        api: '',
        classPath: '',
        orderNo: null as any,
        rate: null as any,
    };
    setTimeout(() => {
        functionPage.value.setInitDate(params);
        state.selectNode = {}
    },100)
}

const deleteFunction = () => {
    if (!state.funcId) {
        $messageBox.warning('请先选择需要删除的数据', '提示');
        return;
    }
    ElMessageBox({
        title: '删除确认',
        message: h('p', null, [
            h('span', null, '是否确定删除功能'),
            h('i', { style: 'color: teal' }, state.selectRow.funcCode),
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                instance.confirmButtonText = '正在删除...'
                deleteFunctionSave(instance,done);
            } else {
                done()
            }
        },
    })
}

function deleteFunctionSave(instance,done) {
    if (state.funcId) {
        const params = {
            funcId: state.funcId,
        };
        setTimeout(() => {
            $api.common.send.post('function0006',params)
                .then(() => {
                    done();
                    instance.confirmButtonLoading = false
                    $messageBox.success('删除成功', '提示');
                    state.funcId = '';
                    state.selectRow = {};
                    functionTable.value.refresh();
                    state.selectNode = [];
                    state.functionInfo = null;
                    functionPage.value.setInitDate(null);
                })
                .catch(() => {
                    done();
                    instance.confirmButtonLoading = false
                });
        }, 100);
    } else {
        $messageBox.warning('请先选择需要删除的数据', '提示');
    }
}

function clearData(){
    state.funcId = '';
    state.selectRow = {};
    state.functionInfo = {}
}

//------------------初始化------------------------------
// const params = {
//     dictFields: 'FUNCSOURCETYPE',
// };
// $api.common.getBatchDict.post(params).then((res) => {
//     state.dictData = res.result;
// });
</script>

<style lang="less" scoped>

</style>